<script setup>
import requestUtil, {getServerUrl} from "@/utils/request"
import {ref} from "vue";
import {Search, Delete, DocumentAdd, Edit, Tools, RefreshRight, QuestionFilled} from "@element-plus/icons-vue"
import {ElMessage, ElMessageBox} from "element-plus";
import Dialog from "@/views/sys/user/components/dialog.vue";
import RoleDialog from "@/views/sys/user/components/roleDialog.vue"

const tableData = ref([])
const count = ref(0)
const searchData = ref({
  query: '',
  pageNum: 1,
  pageSize: 10,
})

const dialogVisible = ref(false)
const dialogTitle = ref("")
const id = ref(-1)

const delBtnStatus = ref(true)
const multipleSelection = ref([])

const roleDialogVisible = ref(false)
const sysRoleList = ref([])

const twoAuthStatus = ref(0)

const authStatusChangeHandle = async () => {
  let res = await requestUtil.post('user/update/two/auth', {"status": twoAuthStatus.value})
  let data = res.data
  if (data.code === 200) {
    ElMessage.success('修改成功')
  } else {
    ElMessage.error(data.msg)
  }
}

const handleSwitchChange = (newValue) => {
  const action = newValue === 1 ? '启用' : '禁用';

  ElMessageBox.confirm(
      `确定要${action}双重认证吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        customStyle: {
          marginTop: '-45vh', // 距离顶部 20% 视口高度
        },
      }
  ).then(() => {
    // 用户确认，状态已经改变
    authStatusChangeHandle();
  }).catch(() => {
    // 用户取消，恢复原来的状态
    twoAuthStatus.value = newValue === 1 ? 0 : 1;
  });
};

const initAuthStatus = async () => {
  let res = await requestUtil.get('user/update/two/auth')
  let data = res.data
  if (data.code === 200) {
    twoAuthStatus.value = data.msg
  } else {
    ElMessage.error(data.msg)
  }
}
initAuthStatus()

const handleRoleDialogValue = (userId, roleList) => {
  id.value = userId;
  sysRoleList.value = roleList;
  roleDialogVisible.value = true;
}

const handleDialogValue = (userId) => {
  if (userId) {
    id.value = userId;
    dialogTitle.value = '用户修改'
  } else {
    id.value = -1;
    dialogTitle.value = '用户添加'
  }
  dialogVisible.value = true
}

const initTableData = async () => {
  const res = await requestUtil.post("user/search", searchData.value)
  if (res.data.code === 200) {
    tableData.value = res.data.msg
    count.value = res.data.count
  }
}
initTableData()

const handleSizeChange = (pageSize) => {
  searchData.value.pageNum = 1;
  searchData.value.pageSize = pageSize;
  initTableData();
}

const handleCurrentChange = (pageNum) => {
  searchData.value.pageNum = pageNum;
  initTableData();
}

const statusChangeHandle = async (row) => {
  let res = await requestUtil.post('user/update/status', row)
  let data = res.data
  if (data.code === 200) {
    ElMessage.success('修改成功')
  } else {
    ElMessage.error(data.msg)
  }
}

const handleResetPassword = async (id) => {
  let res = await requestUtil.post('user/reset/pwd', id)
  let data = res.data
  if (data.code === 200) {
    ElMessage.success('重置成功')
  } else {
    ElMessage.error(data.msg)
  }
}

const handleDelete = async (id) => {
  let idList = []
  if (id) {
    idList.push(id)
  } else {
    multipleSelection.value.forEach(row => {
      idList.push(row.id)
    })
  }
  let res = await requestUtil.del('user/del/user', idList)
  let data = res.data
  if (data.code === 200) {
    ElMessage.success('删除成功');
    await initTableData();
  } else {
    ElMessage.error(data.msg)
  }
}

const handleSelectionChange = (selection) => {
  // 过滤掉用户名为 'admin' 的用户
  multipleSelection.value = selection.filter(row => row.username !== 'admin');
  delBtnStatus.value = multipleSelection.value.length === 0;
}
</script>

<template>
  <div class="app-container">
    <el-card class="box-card">
      <template v-slot:header>
        <div class="space-between">
          <div>
            <el-text class="width-class">用户名:</el-text>
            <el-input class="width-class" style="width: 300px" placeholder="请输入用户名..." v-model="searchData.query"
                      clearable></el-input>
            <el-button type="primary" :icon="Search" @click="initTableData">搜索</el-button>
            <el-button type="warning" :icon="DocumentAdd" @click="handleDialogValue()">新增</el-button>
            <el-popconfirm title="您确定要批量删除这些记录吗？" @confirm="handleDelete(null)">
              <template #reference>
                <el-button type="danger" :disabled="delBtnStatus" :icon="Delete">批量删除</el-button>
              </template>
            </el-popconfirm>
          </div>
          <div>
            <el-text>
              <el-tooltip content="需要用户名密码，和邮箱验证码才能登陆" placement="right">
                <el-icon>
                  <QuestionFilled style="color: red"/>
                </el-icon>
              </el-tooltip>
              邮箱验证：
            </el-text>
            <el-switch v-model="twoAuthStatus"
                       @change="handleSwitchChange"
                       active-text="启用"
                       inactive-text="禁用"
                       :active-value="1"
                       :inactive-value="0">
            </el-switch>
          </div>
        </div>
      </template>

      <el-table
          :data="tableData"
          height="600px"
          stripe
          style="width: 100%"
          @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"/>
        <el-table-column prop="avatar" label="头像" width="80" align="center">
          <template v-slot="scope">
            <img :src="getServerUrl()+'media/userAvatar/'+scope.row.avatar"
                 width="50" height="50"/>
          </template>
        </el-table-column>
        <el-table-column prop="username" label="用户名" width="100"
                         align="center"/>
        <el-table-column prop="roles" label="拥有角色" width="200" align="center">
          <template v-slot="scope">
            <el-tag size="small" type="warning" v-for="(item, index) in scope.row.roleList" :key="index"> {{
                item.name
              }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="200" align="center"/>
        <el-table-column prop="phone_number" label="手机号" width="120"
                         align="center"/>
        <el-table-column prop="status" label="状态" width="200" align="center">
          <template v-slot="{row}">
            <el-switch v-if="row.username !== 'admin'"
                       v-model="row.status"
                       @change="statusChangeHandle(row)"
                       active-text="正常"
                       inactive-text="禁用"
                       :active-value="1"
                       :inactive-value="0">
            </el-switch>
            <el-switch v-else
                       v-model="row.status"
                       active-text="正常"
                       inactive-text="禁用"
                       :active-value="1"
                       :inactive-value="0"
                       disabled>
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="create_time" label="创建时间" width="200"
                         align="center"/>
        <el-table-column prop="login_date" label="最后登录时间" width="200"
                         align="center"/>
        <el-table-column prop="remark" label="备注"/>
        <el-table-column prop="action" label="操作" width="400" fixed="right"
                         align="center">
          <template v-slot="scope">
            <el-button v-if="scope.row.username!=='admin'" type="primary" :icon="Tools"
                       @click="handleRoleDialogValue(scope.row.id,scope.row.roleList)">分配角色
            </el-button>
            <el-popconfirm v-if="scope.row.username!=='admin'" title="是否重置密码？密码：123456"
                           @confirm="handleResetPassword(scope.row.id)">
              <template #reference>
                <el-button type="warning" :icon="RefreshRight">重置密码</el-button>
              </template>
            </el-popconfirm>
            <el-button type="primary" v-if="scope.row.username!=='admin'" :icon="Edit"
                       @click="handleDialogValue(scope.row.id)"></el-button>
            <el-popconfirm v-if="scope.row.username!=='admin'" title="您确定要删除这条记录吗？"
                           @confirm="handleDelete(scope.row.id)">
              <template #reference>
                <el-button type="danger" :icon="Delete"/>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <Dialog v-model="dialogVisible" :dialogVisible="dialogVisible" :id="id" :dialogTitle="dialogTitle"
            @initTableData="initTableData"></Dialog>
    <RoleDialog v-model="roleDialogVisible" :sysRoleList="sysRoleList" :roleDialogVisible="roleDialogVisible" :id="id"
                @initTableData="initTableData"></RoleDialog>
  </div>
  <el-pagination
      :hide-on-single-page="true"
      v-model:currentPage="searchData.pageNum"
      v-model:page-size="searchData.pageSize"
      :page-sizes="[10, 20, 30, 40]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="count"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
  />
</template>

<style scoped lang="scss">
.space-between {
  display: flex;
  align-items: center;
  height: 24px;
  justify-content: space-between;

  .width-class {
    margin-right: 10px;
  }
}

.el-pagination {
  float: right;
  padding: 20px;
  box-sizing: border-box;
}

:deep(th.el-table__cell) {
  word-break: break-word;
  color: var(--text-color);
  height: 40px;
  font-size: 13px;
}

.el-tag--small {
  margin-left: 5px;
}
</style>
